package com.probox.common.entity.service.customer.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.enums.*;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.exception.CustomException;
import com.probox.common.core.utils.DateUtils;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.ServletUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.core.utils.ip.IpUtils;
import com.probox.common.core.utils.money.MoneyUtils;
import com.probox.common.core.utils.sql.SqlUtil;
import com.probox.common.core.web.domain.AjaxResult;
import com.probox.common.core.web.page.PageDomain;
import com.probox.common.core.web.page.TableSupport;
import com.probox.common.entity.domain.customer.*;
import com.probox.common.entity.domain.order.OrderInfoItem;
import com.probox.common.entity.domain.order.OrderRecharge;
import com.probox.common.entity.mapper.customer.*;
import com.probox.common.entity.mapper.system.SysUserMapper;
import com.probox.common.entity.service.common.SysReginService;
import com.probox.common.entity.service.customer.*;
import com.probox.common.entity.service.order.IOrderInfoItemService;
import com.probox.common.entity.service.order.IOrderRechargeService;
import com.probox.common.entity.service.system.ISysUserService;
import com.probox.common.entity.service.wechat.WechatMiniService;
import com.probox.common.entity.vo.StaticQueryVo;
import com.probox.common.entity.vo.WeCom.WeComCustomerVo;
import com.probox.common.entity.vo.customer.*;
import com.probox.common.entity.vo.customer.CustomerInfoVo;
import com.probox.common.entity.vo.customer.CustomerLevelPrivleageVo;
import com.probox.common.entity.vo.customer.CustomerLevelVo;
import com.probox.common.entity.vo.customer.open.CustomerFundOpenVo;
import com.probox.common.redis.service.RedisService;
import com.probox.customer.api.domain.*;
import com.probox.customer.api.domain.CustomerPrivilegeVo;
import com.probox.order.api.domain.OrderQuery;
import com.probox.systemApi.domain.SysUser;
import com.probox.wechat.api.domain.WxQrCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 客户信息Service业务层处理
 *
 * @author zsy
 * @date 2021-05-25
 */
@Service
@Transactional
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements ICustomerInfoService {
    @Autowired
    private CustomerLevelMapper customerLevelMapper;

    @Autowired
    private CustomerInfoMapper customerInfoMapper;

    @Autowired
    private CustomerInfoAccountServiceImpl customerInfoAccountService;

    @Autowired
    private CustomerInfoAccountMapper customerInfoAccountMapper;

    @Autowired
    private CustomerFundMapper customerFundMapper;


    @Autowired
    private SysReginService sysReginService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ICustomerLevelInfoService customerLevelInfoService;

    @Autowired
    private ICustomerLevelService customerLevelService;

    @Autowired
    private WechatMiniService wechatMiniService;

    @Autowired
    private ICustomerFundService customerFundService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ICustomerPrivilegeService customerPrivilegeService;

    @Autowired
    private ICustomerTaskInfoService customerTaskInfoService;

    @Autowired
    private ICustomerHiddenLabelService customerHiddenLabelService;

    @Autowired
    private ICustomerLabelInfoService customerLabelInfoService;

    @Autowired
    private ICustomerFundStoreService customerFundStoreService;


    @Autowired
    private ICustomerFundDetailService customerFundDetailService;

    @Autowired
    private IOrderRechargeService orderRechargeService;

    @Autowired
    private IOrderInfoItemService orderInfoItemService;

    @Autowired
    private ICustomerCollectService customerCollectService;


    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static String customerInfoKey = CachePrefix.CUSTOMER_INFO_DETAIL;


    private Long getAccountByCustomerId(Long customerId) {
        QueryWrapper<CustomerInfoAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_uid", customerId);
        queryWrapper.eq("account_status", DataStatus.valid.getKey());
        CustomerInfoAccount account = customerInfoAccountMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(account)) throw new BaseException("账号不存在");
        return account.getCustomerAccountUid();
    }


    /**
     * 用户行为查询:进入小程序多少次
     *
     * @return
     */
    @Override
    public Integer getOpenTimesByUid(StaticQueryVo vo) {
        return customerInfoMapper.getOpenTimesByUid(vo.getAccountId(), vo.getStartTime(), vo.getEndTime());
    }

    /**
     * 用户行为查询:查询客户停留页面数据
     *
     * @param vo
     * @return
     */
    public HashMap selectPageVisit(StaticQueryVo vo) {
        HashMap page = new HashMap();
        List<Map> mapList = customerInfoMapper.selectPageVisit(vo.getAccountId(), vo.getStartTime(), vo.getEndTime());
        List<String> yAxis = new ArrayList<>(mapList.size());
        List<HashMap> series = new ArrayList<>();
        HashMap totalTime = new HashMap();
        totalTime.put("name", "平均时长");
        List<Long> totalTimeList = new ArrayList<>(mapList.size());
        totalTime.put("data", totalTimeList);
        HashMap maxTime = new HashMap();
        maxTime.put("name", "最大时长");
        List<Long> maxTimeList = new ArrayList<>(mapList.size());
        maxTime.put("data", maxTimeList);
        HashMap times = new HashMap();
        times.put("name", "次数");
        List<Long> timesList = new ArrayList<>(mapList.size());
        times.put("data", timesList);
        series.add(totalTime);
        series.add(maxTime);
        series.add(times);
        mapList.stream().forEach(map -> {
            yAxis.add(Convert.toStr(map.get("page_name")));
            totalTimeList.add(Convert.toLong(map.get("total_time")));
            maxTimeList.add(Convert.toLong(map.get("max_time")));
            timesList.add(Convert.toLong(map.get("times")));
        });
        /**
         * 横轴
         */
        page.put("yAxis", yAxis);
        /**
         * 纵轴
         */
        page.put("series", series);
        return page;
    }

    /**
     * 用户行为查询:查询商品行为数据
     *
     * @return
     */
    public HashMap productAction(StaticQueryVo vo) {
        HashMap productAction = new HashMap();

        List<Map> mapList = customerInfoMapper.listProductAction(vo.getAccountId(), vo.getCustomerId(), vo.getStartTime(), vo.getEndTime());
        List<String> yAxis = new ArrayList<>(mapList.size());
        List<HashMap> series = new ArrayList<>();
        HashMap glanceOver = new HashMap();
        glanceOver.put("name", ProductActionEnum.GlanceOver.getValue());
        List<Long> glanceOverList = new ArrayList<>(mapList.size());
        glanceOver.put("data", glanceOverList);
        HashMap additionalPurchase = new HashMap();
        additionalPurchase.put("name", ProductActionEnum.AdditionalPurchase.getValue());
        List<Long> additionalPurchaseList = new ArrayList<>(mapList.size());
        additionalPurchase.put("data", additionalPurchaseList);
        HashMap placeOrder = new HashMap();
        placeOrder.put("name", ProductActionEnum.PlaceOrder.getValue());
        List<Long> placeOrderList = new ArrayList<>(mapList.size());
        placeOrder.put("data", placeOrderList);
        HashMap purchase = new HashMap();
        purchase.put("name", ProductActionEnum.Purchase.getValue());
        List<Long> purchaseList = new ArrayList<>(mapList.size());
        purchase.put("data", purchaseList);
        series.add(glanceOver);
        series.add(additionalPurchase);
        series.add(placeOrder);
        series.add(purchase);
        mapList.stream().forEach(map -> {
            yAxis.add(Convert.toStr(map.get("pro_name")));
            glanceOverList.add(Convert.toLong(map.get(ProductActionEnum.GlanceOver.getKey())));
            additionalPurchaseList.add(Convert.toLong(map.get(ProductActionEnum.AdditionalPurchase.getKey())));
            placeOrderList.add(Convert.toLong(map.get(ProductActionEnum.PlaceOrder.getKey())));
            purchaseList.add(Convert.toLong(map.get(ProductActionEnum.Purchase.getKey())));
        });
        /**
         * 横轴
         */
        productAction.put("yAxis", yAxis);
        /**
         * 纵轴
         */
        productAction.put("series", series);
        return productAction;
    }

    /**
     * 用户行为查询:查询客户停留页面数据
     */
    @Override
    public AjaxResult getBehavior(StaticQueryVo vo) {
        AjaxResult ajaxResult = AjaxResult.success();
        try {
            vo.setAccountId(getAccountByCustomerId(vo.getCustomerId()));
        }catch (Exception e){
            return ajaxResult;
        }
        if (ObjectUtil.isNotEmpty(vo.getStartTime())) {
            vo.setStartTime(vo.getStartTime() + " 00:00:00");
            vo.setEndTime(vo.getEndTime() + " 23:59:59");
        }

        /**
         * 次数
         */
        ajaxResult.put("openTimes", getOpenTimesByUid(vo));
        /**
         * 页面行为指数
         */

        ajaxResult.put("page", selectPageVisit(vo));
        /**
         * 商品新闻指数
         */
        ajaxResult.put("product", productAction(vo));
        return ajaxResult;
    }

    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (pageNum == null) pageNum = 1;
        if (pageSize == null) pageSize = 10;
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 客户余额详情
     *
     * @param customerId
     * @return
     */
    @Override
    public AjaxResult myBalanceDetail(Long customerId,String businessType) {
        AjaxResult ajaxResult = AjaxResult.success();
        startPage();
        if ("storeBalance".equals(businessType)) {
            /**
             * 储值列表，包含VIP和扫码储值
             */
            HashMap storeBalance = new HashMap();
            //PageHelper.startPage(1, 10);

            List<OrderRecharge> list = orderRechargeService.listOrderRechargeByCustomerId(customerId);

            //List<CustomerFundStoreVo> customerFundStoreVos = customerFundStoreService.listFundStore(customerId);
            storeBalance.put("rows", list);
            storeBalance.put("total", new PageInfo(list).getTotal());
            ajaxResult.put("storeBalance", storeBalance);
        }else if ("orderBalance".equals(businessType)){
            /**
             * 余额消费记录
             */
            HashMap orderBalance = new HashMap();
            //PageHelper.startPage(1, 10);
            List<CustomerFundDetail> fundDetail = customerFundDetailService.getFundDetail(customerId);
            orderBalance.put("rows", fundDetail);
            orderBalance.put("total", new PageInfo(fundDetail).getTotal());
            ajaxResult.put("orderBalance", orderBalance);
        }else if ("coupon".equals(businessType)) {


        }else if ("download".equals(businessType)){
            HashMap downloadList = new HashMap();
            OrderQuery query = new OrderQuery();
            query.setOrderType("good");
            query.setCustomerUid(customerId);
            List<OrderInfoItem> lunwen = orderInfoItemService.selectLuwenOrderList(query);
            downloadList.put("rows", lunwen);
            downloadList.put("total", new PageInfo(lunwen).getTotal());
            ajaxResult.put("lunwenList", downloadList);
        }else if ("maiduan".equals(businessType)){
            HashMap downloadList = new HashMap();
            OrderQuery query = new OrderQuery();
            query.setOrderType("maiduan");
            query.setCustomerUid(customerId);
            List<OrderInfoItem> lunwen = orderInfoItemService.selectLuwenOrderList(query);
            downloadList.put("rows", lunwen);
            downloadList.put("total", new PageInfo(lunwen).getTotal());
            ajaxResult.put("maiduan", downloadList);
        }else if ("collect".equals(businessType)){
            HashMap collectList = new HashMap();
            List<CustomerCollect> collects = customerCollectService.getCustomerCollect(customerId);
            collectList.put("rows", collects);
            collectList.put("total", new PageInfo(collects).getTotal());
            ajaxResult.put("collect", collectList);
        }
        return ajaxResult;
    }


    /**
     * 根据客户编号查询客户详情
     *
     * @param no
     * @return
     */
    @Override
    public WeComCustomerVo getByWeComCustomerVoByNo(String no) {
        WeComCustomerVo vo = new WeComCustomerVo();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("customer_no", no);
        queryWrapper.last(" limit 1");
        CustomerInfo customer = customerInfoMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(customer)) {
            throw new BaseException("客户不存在！");
        }
        BeanUtils.copyProperties(customer, vo);
        vo.setLevelName(customerLevelInfoService.getLevelNameByUid(customer.getCustomerUid()));
        CustomerFund customerFund = customerFundService.getByCustomerId(customer.getCustomerUid());
        vo.setPineappleGoldCoin(customerFund.getBalanceStr());
        vo.setPineappleSilverCoin(customerFund.getRedBagStr());
        vo.setPineappleFlower(customerFund.getScoreStr());
        vo.setCustomerId(customer.getCustomerUid());
        Long storeId = sysUserService.getStoreId(SecurityUtils.getUserId());
        /**
         * 客户档案
         */
        // vo.setCustomerProfileList(customerServiceSubscribeRecordService.listCustomerItem(customerId));
        //vo.setCustomerProfileList(customerServiceSubscribeRecordService.serviceAppointmentByDay(null, SubscribeStatusEnum.ServiceRecord.getKey(), customer.getCustomerUid(), 0, 0, null));
        /**
         * 卡耗情况
         */

        /**
         * 充值和消费明细
         */
        vo.setWeComConsumptionVoS(customerInfoMapper.listCustomerConsumptionByCustomerId(customer.getCustomerUid(), storeId));
        return vo;
    }


    /**
     * 企业微信段查看客户的信息
     *
     * @param customerId
     * @return
     */
    @Override
    public WeComCustomerVo getByWeComCustomerVo(Long customerId) {
        WeComCustomerVo vo = new WeComCustomerVo();
        CustomerInfo customer = this.getById(customerId);
        BeanUtils.copyProperties(customer, vo);
        vo.setCustomerId(customer.getCustomerUid());
        vo.setLevelName(customerLevelInfoService.getLevelNameByUid(customerId));
        CustomerFund customerFund = customerFundService.getByCustomerId(customerId);
        vo.setPineappleGoldCoin(customerFund.getBalanceStr());
        vo.setPineappleSilverCoin(customerFund.getRedBagStr());
        vo.setPineappleFlower(Convert.toStr(customerFund.getScore()));
        Long storeId = sysUserService.getStoreId(SecurityUtils.getUserId());

        /**
         * 充值和消费明细
         */
        vo.setWeComConsumptionVoS(customerInfoMapper.listCustomerConsumptionByCustomerId(customerId, storeId));
        return vo;
    }

    /**
     * 根据手机号查询客户名称
     *
     * @param phone
     * @return
     */
    @Override
    public CustomerInfoVo getName(String phone) {
        QueryWrapper<CustomerInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        queryWrapper.eq("status", DataStatus.valid.getKey());
        CustomerInfo customerInfo = customerInfoMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(customerInfo)) throw new BaseException("该手机不存在客户!");
        CustomerInfoVo customerInfoVo = new CustomerInfoVo();
        BeanUtils.copyProperties(customerInfo, customerInfoVo);
        customerInfoVo.setLevelName(customerLevelInfoService.getLevelNameByUid(customerInfo.getCustomerUid()));
        return customerInfoVo;
    }

    /**
     * 模糊查询手机号
     *
     * @param phone
     * @return
     */
    @Override
    public List<CustomerInfo> listPhone(String phone) {
        if (ObjectUtil.isEmpty(phone)) return new ArrayList<>();
        QueryWrapper<CustomerInfo> queryWrapper = new QueryWrapper<>();
//        queryWrapper.like("phone", phone);
        queryWrapper.and(i -> i.like("phone", phone).or().like("customer_name", phone).or().like("customer_no", phone));
        queryWrapper.eq("status", DataStatus.valid.getKey());
        List<CustomerInfo> customerInfos = customerInfoMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(customerInfos)) {
            return customerInfos.stream().map(customerInfo -> {
                CustomerInfoVo customerInfoVo = new CustomerInfoVo();
                BeanUtils.copyProperties(customerInfo, customerInfoVo);
                //customerInfoVo.setLevelName(customerLevelInfoService.getLevelNameByUid(customerInfo.getCustomerUid()));
                if (customerInfoVo.getPhone() == null){
                    customerInfoVo.setPhone("微信登录");
                }
                return customerInfoVo;
            }).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public List<CustomerInfo> listByCity(List<String> citys, List<Long> customerIds) {
        //if (ObjectUtil.isEmpty(citys)) return new ArrayList<>();
        QueryWrapper<CustomerInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", DataStatus.valid.getKey());
        if (citys.size()>0) {
            queryWrapper.and(wrapper -> wrapper.in("city", citys).or().in("province", citys));
        }
        if (customerIds != null && customerIds.size() > 0) {
            queryWrapper.in("CUSTOMER_UID", customerIds);
        }
        return customerInfoMapper.selectList(queryWrapper);
    }


    @Override
    public List<CustomerInfo> listByBirthday(List<String> citys) {
        String date = DateUtil.format(new Date(), "MM-dd");
        QueryWrapper<CustomerInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("birthday", "%" + date);
        queryWrapper.eq("status", DataStatus.valid.getKey());
        if (citys != null && citys.size() > 0) {
            queryWrapper.and(wrapper -> wrapper.in("city", citys).or().in("province", citys));
        }
        return customerInfoMapper.selectList(queryWrapper);
    }


    /**
     * 查询客户信息
     *
     * @param customerUid 客户信息ID
     * @return 客户信息
     */
    @Override
    public AjaxResult selectCustomerInfoById(Long customerUid) {
        AjaxResult ajax = AjaxResult.success();
        CustomerInfo customer = this.getById(customerUid);
        CustomerInfoVo customerInfoVo = new CustomerInfoVo();
        BeanUtils.copyProperties(customer, customerInfoVo);
        Long[] region = new Long[3];
        if (customer.getProvinceCode() != null && customer.getCityCode() != null && customer.getAreaCode() != null) {
            region[0] = Long.parseLong(customer.getProvinceCode());
            region[1] = Long.parseLong(customer.getCityCode());
            region[2] = Long.parseLong(customer.getAreaCode());
        }
        customerInfoVo.setRegion(region);
        customerInfoVo.setLevelName(customerLevelInfoService.getLevelNameByUid(customerUid));
        ajax.put("customer", customerInfoVo);


        return ajax;
    }


    /**
     * 查询客户信息列表
     *
     * @param customerInfo 客户信息
     * @return 客户信息
     */
    @Override
    public List<CustomerInfoLevelVo> queryList(CustomerInfoVo customerInfo) {
        customerInfo.setPlatformUid(SecurityUtils.getPlatformId());
        if (customerInfo.getCreateTimeArr() != null) {
            if (customerInfo.getCreateTimeArr().size() > 0) {
                customerInfo.setStartCreateTime(String.valueOf(customerInfo.getCreateTimeArr().get(0)));
                customerInfo.setEndCreateTime(String.valueOf(customerInfo.getCreateTimeArr().get(1)));
            }
        }
        List<CustomerInfoLevelVo> customerInfoVoList = customerInfoMapper.selectCustomerLevel(customerInfo);
        for (CustomerInfoLevelVo infoLevelVo : customerInfoVoList) {
            List<CustomerLevelInfoVo> customerLevelInfoVoList = infoLevelVo.getCustomerLevelInfoVoList();
            if (customerLevelInfoVoList.size() > 1) {
                for (CustomerLevelInfoVo levelInfoVo : customerLevelInfoVoList) {
                    CustomerLevelVo customerLevelVo = levelInfoVo.getCustomerLevelVo();
                    infoLevelVo.setLevelUid(customerLevelVo.getLevelId());
                    infoLevelVo.setLevelName(customerLevelVo.getLevelName());
                }
            }
            if (customerLevelInfoVoList.size() == 1) {
                infoLevelVo.setLevelUid(infoLevelVo.getCustomerLevelInfoVoList().get(0).getCustomerLevelVo().getLevelId());
                infoLevelVo.setLevelName(infoLevelVo.getCustomerLevelInfoVoList().get(0).getCustomerLevelVo().getLevelName());
            }
//            //判断客户账号是否锁定
//            QueryWrapper<CustomerInfoAccount> infoAccountQueryWrapper = new QueryWrapper<>();
//            infoAccountQueryWrapper.eq("CUSTOMER_UID", infoLevelVo.getCustomerUid());
//            infoAccountQueryWrapper.eq("ACCOUNT_STATUS", CustomerAccountStatusTypeEnum.lock.getKey());
//            infoAccountQueryWrapper.select("CUSTOMER_ACCOUNT_UID");
//            List<CustomerInfoAccount> customerInfoAccountList = customerInfoAccountMapper.selectList(infoAccountQueryWrapper);
//            if (customerInfoAccountList.size() > 0) {
//                infoLevelVo.setAccountStatus(CustomerAccountStatusTypeEnum.lock.getKey());
//            } else {
//                infoLevelVo.setAccountStatus(CustomerAccountStatusTypeEnum.start.getKey());
//            }
        }

        return customerInfoVoList;
    }

    /**
     * 新增客户信息
     *
     * @param customerInfoVo 客户信息
     * @return 结果
     */
    @Override
    public boolean insertCustomerInfo(CustomerInfoVo customerInfoVo) {
        return insertCustomerAndAccount(customerInfoVo, customerInfoVo.getPassword());
    }


    /**
     * 修改客户信息
     *
     * @param customerInfoVo 客户信息
     * @return 结果
     */
    @Override
    public boolean updateCustomerInfo(CustomerInfoVo customerInfoVo) {
        customerInfoVo.setUpdateUser(SecurityUtils.getUserId());
        customerInfoVo.setUpdateName(SecurityUtils.getUsername());
        customerInfoVo.setUpdateTime(DateUtil.date());
        customerInfoVo.setCustomerUid(SecurityUtils.getCustomerUid());
        //updateCustomerAccount(customerInfoVo.getCustomerUid(), customerInfoVo.getPassword(), customerInfoVo.getStatus());
        return this.updateById(customerInfoVo);
    }

    /**
     * 修改客户账号
     *
     * @param customerId
     * @param password
     */
    public void updateCustomerAccount(Long customerId, String password, String status) {
        if (StringUtils.isEmpty(password) && StringUtils.isEmpty(status)) {
            password = "123456";
        }
        QueryWrapper<CustomerInfoAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CUSTOMER_UID", customerId);
        List<CustomerInfoAccount> customerInfoAccountList = customerInfoAccountMapper.selectList(queryWrapper);
        if (customerInfoAccountList != null) {
            for (CustomerInfoAccount account : customerInfoAccountList) {
                if (DataStatus.valid.getKey().equals(status)) {
                    account.setAccountStatus(CustomerAccountStatusTypeEnum.start.getKey());
                } else {
                    account.setAccountStatus(CustomerAccountStatusTypeEnum.lock.getKey());
                }
                account.setUpdateName(SecurityUtils.getUsername());
                account.setUpdateDate(DateUtil.date());
                account.setUpdateUser(SecurityUtils.getUserId());
                if (account.getAccountPassword() != null) {
                    account.setAccountPassword(SecurityUtils.encryptPassword(password));
                }
                customerInfoAccountMapper.updateById(account);
            }
        }
    }

    /**
     * 批量删除客户信息
     *
     * @param customerUids 需要删除的客户信息ID
     * @return 结果
     */
    @Override
    public boolean deleteCustomerInfoByIds(Long[] customerUids) {
        UpdateWrapper<CustomerInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("CUSTOMER_UID", Arrays.asList(customerUids));
        updateWrapper.set("STATUS", DataStatus.delete.getKey());
        return this.update(updateWrapper);
    }

    @Override
    public String importUser(List<CustomerInfo> customerInfoList, String password) {
        if (StringUtils.isNull(customerInfoList) || customerInfoList.size() == 0) {
            throw new CustomException("导入客户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (CustomerInfo customerInfo : customerInfoList) {
            try {
                String[] labels = new String[3];
                labels[0] = customerInfo.getProvince();
                labels[1] = customerInfo.getCity();
                labels[2] = customerInfo.getArea();
                Long[] reginCode = sysReginService.getReginCode(labels);
                if (reginCode != null && reginCode.length == 3) {
                    customerInfo.setProvinceCode(String.valueOf(reginCode[0]));
                    customerInfo.setCityCode(String.valueOf(reginCode[1]));
                    customerInfo.setAreaCode(String.valueOf(reginCode[2]));
                } else {
                    throw new CustomException("省市区填写错误,请输入正确的省市区名称如：湖南省,长沙市,岳麓区");
                }
                CustomerInfoVo customerInfoVo = new CustomerInfoVo();
                BeanUtils.copyProperties(customerInfo, customerInfoVo);
                insertCustomerAndAccount(customerInfoVo, password);
                successNum++;
                successMsg.append("<br/>" + successNum + "、账号 " + customerInfo.getCustomerName() + " 导入成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + customerInfo.getCustomerName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    @Override
    public CustomerVo getCustomerVo(Long customerId) {
        //判断当前客户账号是否锁定
        Boolean isLockAccount = customerInfoAccountService.getIsLockAccount(customerId);
        if (isLockAccount == false) {
            throw new CustomException("当前客户账号已锁定");
        }
        CustomerVo rst = null;
        CustomerInfo ci = this.getById(customerId);
        if (ci != null) {
            rst = new CustomerVo();
            BeanUtils.copyProperties(ci, rst);
            //判断当前客户绑定的等级信息
            CustomerLevelInfo levelInfo = new CustomerLevelInfo();
            QueryWrapper<CustomerFund> fundQueryWrapper = new QueryWrapper<>();
            fundQueryWrapper.eq("CUSTOMER_UID", customerId);
            CustomerFund customerFund = customerFundMapper.selectOne(fundQueryWrapper);
            List<CustomerLevelInfo> customerBindLevelInfoList = customerLevelInfoService.getCustomerBindLevelInfo(customerId, customerFund.getFundUid(), rst.getPlatformUid());
            if (customerBindLevelInfoList.size() > 1) {
                for (CustomerLevelInfo customerLevelInfo : customerBindLevelInfoList) {
                    CustomerLevel customerLevel = customerLevelMapper.selectById(customerLevelInfo.getLevelUid());
                    if (CustomerLevelPatternTypeEnum.payMode.getKey().equals(customerLevel.getCustomerPattern())) {
                        levelInfo = customerLevelInfo;
                    }
                }
            } else if (customerBindLevelInfoList.size() == 1) {
                levelInfo = customerBindLevelInfoList.get(0);
            }
            if (levelInfo.getLevelUid() != null) {
                logger.info("获取到绑定等级id:" + levelInfo.getLevelUid());
                CustomerLevelVo levelVo = customerLevelService.getlevelInfoDetailOpen(levelInfo.getLevelUid(), rst.getPlatformUid());
                if (levelVo != null) {
                    com.probox.customer.api.domain.CustomerLevelVo lv = new com.probox.customer.api.domain.CustomerLevelVo();
                    //复制
                    List<CustomerLevelPrivleageVo> customerLevelPrivleageVosList = levelVo.getCustomerLevelPrivleageVos();
                    List<com.probox.customer.api.domain.CustomerLevelPrivleageVo> apilist = new ArrayList<>();
                    customerLevelPrivleageVosList.forEach(customerLevelPrivleageVo -> {
                        com.probox.customer.api.domain.CustomerLevelPrivleageVo vo = new com.probox.customer.api.domain.CustomerLevelPrivleageVo();
                        BeanUtils.copyProperties(customerLevelPrivleageVo, vo);
                        apilist.add(vo);
                    });
                    BeanUtils.copyProperties(levelVo, lv);
                    lv.setCustomerLevelPrivleageVos(apilist);
                    rst.setCustomerLevelVo(lv);
                    List<CustomerPrivilegeVo> list = new ArrayList<>();
//                    Long PlatformUid = SecurityUtils.getCustomerPlatformUid();
//                    CustomerLevelVo customerLevelVo = customerLevelMapper.getLevelPrivilegeInfo(levelVo.getLevelId(),rst.getPlatformUid());
                    List<CustomerLevelPrivleageVo> customerLevelPrivleageVos = levelVo.getCustomerLevelPrivleageVos();
                    for (CustomerLevelPrivleageVo privleageVo : customerLevelPrivleageVos) {
                        CustomerPrivilegeVo customerPrivilegeVo = new CustomerPrivilegeVo();
                        customerPrivilegeVo.setCustomerPrivilegeUid(privleageVo.getCustomerPrivilegeUid());
                        customerPrivilegeVo.setPlatformId(privleageVo.getPlatformId());
                        customerPrivilegeVo.setPrivilegeUid(privleageVo.getPrivleageId());
                        customerPrivilegeVo.setLevelUid(levelVo.getLevelId());
                        customerPrivilegeVo.setPrivilegeValue(privleageVo.getPrivilegeValue());
                        if (privleageVo.getPrivilegeStatus() == true) {
                            customerPrivilegeVo.setPrivilegeStatus("0");
                        } else {
                            customerPrivilegeVo.setPrivilegeStatus("1");
                        }
                        customerPrivilegeVo.setDataStatus(privleageVo.getDataStatus());
                        customerPrivilegeVo.setPrivilegeName(privleageVo.getPrivleageName());
                        customerPrivilegeVo.setPrivilegeShowname(privleageVo.getPrivleageShowName());
                        customerPrivilegeVo.setPrivilegeImages(privleageVo.getPrivilegeImages());
                        customerPrivilegeVo.setPrivilegeIntroduce(privleageVo.getPrivilegeIntroduce());
                        customerPrivilegeVo.setIsUpgrade(privleageVo.getIsUpgrade());
                        customerPrivilegeVo.setIsGiveType(privleageVo.getIsGive());
                        customerPrivilegeVo.setPlatformUnit(privleageVo.getPlatformUnit());
                        list.add(customerPrivilegeVo);
                    }
                    rst.setPrivilegeList(list);
//                    List<com.probox.customer.vo.CustomerPrivilegeVo> ps = levelVo.getCustomerPrivileges();
//                    if (ps != null && ps.size()>0) {
//                        for (com.probox.customer.vo.CustomerPrivilegeVo po : ps) {
//                            CustomerPrivilegeVo tmp = new CustomerPrivilegeVo();
//                            BeanUtils.copyProperties(po, tmp);
//                            list.add(tmp);
//                        }
//                    }
                }
            }
            QueryWrapper<CustomerInfoAccount> accountQueryWrapper = new QueryWrapper<>();
            accountQueryWrapper.eq("CUSTOMER_UID", customerId);
            List<CustomerInfoAccount> customerInfoAccountList = customerInfoAccountMapper.selectList(accountQueryWrapper);
            for (CustomerInfoAccount account : customerInfoAccountList) {
                if (account.getOpenId() != null) {
                    rst.setOpenID(account.getOpenId());
                }
            }
        }
        return rst;
    }

    @Override
    public CustomerInfo getCustomerByPhone(String phone) {
        QueryWrapper<CustomerInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        List<CustomerInfo> list = customerInfoMapper.selectList(queryWrapper);
        if (list.size()>0){
            return list.get(0);
        }
        return null;
    }

    @Override
    public CustomerVo getNewCustomerVo(Long customerId) {
        Boolean isLockAccount = customerInfoAccountService.getIsLockAccount(customerId);
        if (isLockAccount == false) {
            throw new CustomException("当前客户账号已锁定");
        }
        CustomerVo rst = null;
        CustomerInfo ci = this.getById(customerId);
        if (ci != null) {
            rst = new CustomerVo();
            BeanUtils.copyProperties(ci, rst);
            //判断当前客户绑定的等级信息
            CustomerLevelInfo levelInfo = null;
            QueryWrapper<CustomerFund> fundQueryWrapper = new QueryWrapper<>();
            fundQueryWrapper.eq("CUSTOMER_UID", customerId);
            CustomerFund customerFund = customerFundMapper.selectOne(fundQueryWrapper);
            List<CustomerLevelInfo> customerBindLevelInfoList = customerLevelInfoService.getCustomerBindLevelInfo(customerId, customerFund.getFundUid(), rst.getPlatformUid());
            if (customerBindLevelInfoList.size() > 1) {
                for (CustomerLevelInfo customerLevelInfo : customerBindLevelInfoList) {
                    CustomerLevel customerLevel = customerLevelMapper.selectById(customerLevelInfo.getLevelUid());
                    if (CustomerLevelPatternTypeEnum.payMode.getKey().equals(customerLevel.getCustomerPattern())) {
                        levelInfo = customerLevelInfo;
                    }
                }
            } else if (customerBindLevelInfoList.size() == 1) {
                levelInfo = customerBindLevelInfoList.get(0);
            }
            if (levelInfo != null) {
                rst.setMemberGrade(customerLevelService.getById(levelInfo.getLevelUid()).getCustomerGrade().longValue());
                rst.setLevelPrivilegeList(customerPrivilegeService.getLevelAndPrivilege(levelInfo.getLevelUid()));
            } else {
                rst.setMemberGrade(0L);
            }


            QueryWrapper<CustomerInfoAccount> accountQueryWrapper = new QueryWrapper<>();
            accountQueryWrapper.eq("CUSTOMER_UID", customerId);
            List<CustomerInfoAccount> customerInfoAccountList = customerInfoAccountMapper.selectList(accountQueryWrapper);
            for (CustomerInfoAccount account : customerInfoAccountList) {
                if (account.getOpenId() != null) {
                    rst.setOpenID(account.getOpenId());
                }
            }
        }
        return rst;
    }

    @Override
    public HashMap getCustomerInfoDetail(Long customerId) {
        CustomerInfo customerInfo = customerInfoMapper.selectById(customerId);
        QueryWrapper<CustomerInfoAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CUSTOMER_UID", customerInfo.getCustomerUid());
        List<CustomerInfoAccount> customerInfoAccountList = customerInfoAccountMapper.selectList(queryWrapper);
        HashMap customerInfoMap = new HashMap();
        customerInfoMap.put("customerName", customerInfo.getCustomerName());
        customerInfoMap.put("headImage", customerInfo.getHeadImage());
        for (CustomerInfoAccount infoAccount : customerInfoAccountList) {
            if (!StringUtils.isEmpty(infoAccount.getAccountNickName())) {
                customerInfoMap.put("accountNickName", infoAccount.getAccountNickName());
            }
        }
        return customerInfoMap;
    }

    /**
     * 更新客户信息
     *
     * @param customerInfo
     */
    @Override
    public Object editCustomerInfo(CustomerInfo customerInfo) {
        if (SecurityUtils.getCustomerUid() != null) {
            logger.info("更新客户id:{}信息", SecurityUtils.getCustomerUid());
            CustomerInfo info = customerInfoMapper.selectById(SecurityUtils.getCustomerUid());
            info.setCustomerName(customerInfo.getCustomerName());
            info.setSex(customerInfo.getSex());
            info.setProvince(customerInfo.getProvince());
            info.setCity(customerInfo.getCity());
            info.setArea(customerInfo.getArea());
            info.setAllergy(customerInfo.getAllergy());
            info.setSkinOilType(customerInfo.getSkinOilType());
            info.setSkinSensitiveType(customerInfo.getSkinSensitiveType());
            info.setSkinColorType(customerInfo.getSkinColorType());
            info.setSkinCompactType(customerInfo.getSkinCompactType());
            info.setMedicalHistory(customerInfo.getMedicalHistory());
            info.setBirthday(customerInfo.getBirthday());
            if (StringUtils.isNotEmpty(customerInfo.getHeadImage())) {
                info.setHeadImage(customerInfo.getHeadImage());
            }

            String[] labels = new String[3];
            labels[0] = customerInfo.getProvince();
            labels[1] = customerInfo.getCity();
            labels[2] = customerInfo.getArea();
            Long[] reginCode = sysReginService.getReginCode(labels);
            if (reginCode != null && reginCode.length == 3) {
                info.setProvinceCode(String.valueOf(reginCode[0]));
                info.setCityCode(String.valueOf(reginCode[1]));
                info.setAreaCode(String.valueOf(reginCode[2]));
            }
            info.setAddressDetail(customerInfo.getAddressDetail());
            info.setUpdateUser(SecurityUtils.getCustomerUid());
            info.setUpdateName(SecurityUtils.getCustomerUserName());
            info.setUpdateTime(DateUtil.date());
            customerInfoMapper.updateById(info);
            //删除客户基本信息缓存
            redisService.deleteObject(customerInfoKey + SecurityUtils.getCustomerUid());

            if (StringUtils.isNotEmpty(info.getHeadImage()) && StringUtils.isNotEmpty(info.getCustomerName()) && StringUtils.isNotEmpty(info.getSex())
                    && StringUtils.isNotEmpty(info.getArea()) && StringUtils.isNotEmpty(info.getAddressDetail()) && info.getBirthday() != null
                    && StringUtils.isNotEmpty(info.getAllergy()) && StringUtils.isNotEmpty(info.getSkinOilType()) && StringUtils.isNotEmpty(info.getSkinSensitiveType())
                    && StringUtils.isNotEmpty(info.getSkinColorType()) && StringUtils.isNotEmpty(info.getSkinCompactType()) && StringUtils.isNotEmpty(info.getMedicalHistory())
            ) {
                customerTaskInfoService.finishTask(info, TaskCodeEnum.improve_data_task.toString());
            }

        }
        CustomerInfoAccount customerInfoAccount = customerInfoAccountMapper.selectById(SecurityUtils.getCustomerAccountUid());
        customerInfoAccount.setAccountNickName(customerInfo.getCustomerName());
        customerInfoAccount.setAccountHeadImg(customerInfo.getHeadImage());
        customerInfoAccount.setSex(customerInfo.getSex());
        customerInfoAccount.setNation(customerInfo.getNation());
        customerInfoAccount.setProvince(customerInfo.getProvince());
        customerInfoAccount.setCity(customerInfo.getCity());
        customerInfoAccount.setUpdateDate(DateUtil.date());
        if (SecurityUtils.getCustomerUid() != null) {
            customerInfoAccount.setUpdateUser(SecurityUtils.getCustomerUid());
            customerInfoAccount.setUpdateName(SecurityUtils.getCustomerUserName());
        }
        customerInfoAccountMapper.updateById(customerInfoAccount);
        if (customerInfoAccount != null) {
            return "1";
        } else {
            return "0";
        }
    }


    @Override
    public CustomerFundOpenVo geCustomerFundInfo() {
        QueryWrapper<CustomerFund> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("PLATFORM_UID",SecurityUtils.getCustomerPlatformUid());
        queryWrapper.eq("CUSTOMER_UID", SecurityUtils.getCustomerUid());
        queryWrapper.last("order by FUND_UID desc limit 1");
        CustomerFund customerFund = customerFundMapper.selectOne(queryWrapper);
        CustomerFundOpenVo customerFundOpenVo = new CustomerFundOpenVo();
        if (customerFund != null) {
            Integer allFans = customerFund.getAllFans();
            Integer allFansSecond = customerFund.getAllFansSecond();
            customerFundOpenVo.setAllProfit(String.valueOf(customerFund.getProfit()));
            customerFundOpenVo.setAllBalance(MoneyUtils.changeF2Y(customerFund.getBalance()));
            customerFundOpenVo.setAllRedBag(MoneyUtils.changeF2Y(customerFund.getRedBag()));
            customerFundOpenVo.setAllScore(String.valueOf(customerFund.getScore()));
            customerFundOpenVo.setScore(customerFund.getScore());
            customerFundOpenVo.setFreezeScore(customerFund.getFreezeScore());
            customerFundOpenVo.setAllFans(allFans + allFansSecond);
//            customerFundOpenVo = new CustomerFundOpenVo(customerFund.getAllProfitStr(),customerFund.getAllBalanceStr(),customerFund.getAllScore(),allFans+allFansSecond);
        } else {
            customerFundOpenVo.setAllProfit("0");
            customerFundOpenVo.setAllBalance("0");
            customerFundOpenVo.setAllRedBag("0");
            customerFundOpenVo.setAllScore("0");
            customerFundOpenVo.setAllFans(0);
            customerFundOpenVo.setScore(0L);
            customerFundOpenVo.setFreezeScore(0L);
//            customerFundOpenVo = new CustomerFundOpenVo("0.00","0.00",0L,0);
        }
        return customerFundOpenVo;
    }


    /**
     * 查询客户粉丝详细
     *
     * @return
     */
    @Override
    public List<CustomerInfo> getFansDetail() {
        //查询有多少父级id等于当前客户
        QueryWrapper<CustomerInfo> infoQueryWrapper = new QueryWrapper<>();
        infoQueryWrapper.eq("STATUS", DataStatus.valid.getKey());
        infoQueryWrapper.eq("PLATFORM_UID", SecurityUtils.getCustomerPlatformUid());
        infoQueryWrapper.and(wrapper -> wrapper.eq("FATHER_UID", SecurityUtils.getCustomerUid()).or().eq("GRAND_FATHER_UID", SecurityUtils.getCustomerUid()));
        infoQueryWrapper.select("CUSTOMER_UID");
        List<CustomerInfo> customerInfoList = customerInfoMapper.selectList(infoQueryWrapper);
        List<CustomerInfo> customerInfos = new ArrayList<>();
        if (customerInfoList.size() > 0) {
            for (CustomerInfo info : customerInfoList) {
                CustomerInfo customerInfo = customerInfoMapper.selectById(info.getCustomerUid());
                customerInfos.add(customerInfo);
            }
        }
        return customerInfos;
    }

    @Override
    public List<CustomerInfo> getRmfCustomerList() {
        String date = DateUtils.formatDate(new Date());
        QueryWrapper<CustomerInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.last(" where (rmf_update_time<='"+date+"' or rmf_update_time is null ) limit 10 ");
        return customerInfoMapper.selectList(queryWrapper);
    }

    /**
     * 查询客户粉丝详细总条数
     *
     * @return
     */
    @Override
    public Integer getFansDetailCount() {
        //查询有多少父级id等于当前客户
        QueryWrapper<CustomerInfo> infoQueryWrapper = new QueryWrapper<>();
        infoQueryWrapper.eq("FATHER_UID", SecurityUtils.getCustomerUid());
        infoQueryWrapper.eq("STATUS", DataStatus.valid.getKey());
        infoQueryWrapper.eq("PLATFORM_UID", SecurityUtils.getCustomerPlatformUid());
        infoQueryWrapper.select("CUSTOMER_UID");
        List<CustomerInfo> customerInfoList = customerInfoMapper.selectList(infoQueryWrapper);
        List<CustomerInfo> customerInfos = new ArrayList<>();
        if (customerInfoList.size() > 0) {
            for (CustomerInfo info : customerInfoList) {
                CustomerInfo customerInfo = customerInfoMapper.selectById(info.getCustomerUid());
                customerInfos.add(customerInfo);
            }
        }
        return customerInfos.size();
    }

    /**
     * 根据id集合查询客户信息
     *
     * @param customerUids
     * @return
     */
    @Override
    public List<CustomerInfoVo> getCustomerInfoByids(Long[] customerUids) {
        List<CustomerInfoVo> customerInfoVoList = customerInfoMapper.selectCustomerFundInfo(customerUids);
        return customerInfoVoList;
    }

    /**
     * 查看分享者小程序码
     *
     * @param customerUid
     * @return
     */
    @Override
    public String getSharecustomerQrCode(Long customerUid) {
        WxQrCode wxQrCode = new WxQrCode();
        wxQrCode.setAuthorizationType(WechatAuthorizationTypeEnum.applet.getKey());
        wxQrCode.setSharecustomerUid(customerUid);
        wxQrCode.setPlatformId(SecurityUtils.getPlatformId());
        String qrCode = wechatMiniService.getwxacodeunlimit(wxQrCode);
        return qrCode;
    }

    @Override
    public List<CustomerInfoLevelVo> queryListSelf(CustomerInfoVo customerInfo) {


        return customerInfoMapper.queryListSelf(customerInfo);
    }

    /**
     * 企业微信客户列表
     *
     * @param customerInfo
     * @return
     */
    @Override
    public List<WeComCustomerVo> listCustomerByStoreId(CustomerInfoVo customerInfo) {
        customerInfo.setStoreId(SecurityUtils.getStoreId());
        if (customerInfo.getStoreId() == null){
            SysUser user = sysUserService.selectUserById(SecurityUtils.getUserId());
            if (user != null){
                customerInfo.setStoreGroupId(user.getStoreGroupId());
            }
        }
        //如果是搜索，就查全部的会员信息
        if (StringUtils.isNotEmpty(customerInfo.getBusiness())){
            if (customerInfo.getBusiness().equalsIgnoreCase("search")){
                customerInfo.setStoreId(null);
                customerInfo.setStoreGroupId(null);
            }
        }
        PageHelper.startPage(customerInfo.getPageNum(), customerInfo.getPageSize());
        List<WeComCustomerVo> list = customerInfoMapper.listCustomerByStoreId(customerInfo);
        for(WeComCustomerVo cv:list){
            if (StringUtils.isNotEmpty(cv.getContactMan())){
                cv.setCustomerName(cv.getCustomerName()+"("+cv.getContactMan()+")");
            }
        }
        return list;
    }

    /**
     * 新增客户信息与客户账号信息
     *
     * @param customerInfo
     * @return
     */
    public boolean insertCustomerAndAccount(CustomerInfoVo customerInfo, String password) {
        try {
            if (StringUtils.isEmpty(password)) {
                password = "123456";
            }
            QueryWrapper<CustomerInfo> infoQueryWrapper = new QueryWrapper<>();
            infoQueryWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
            infoQueryWrapper.eq("PHONE", customerInfo.getPhone());
            infoQueryWrapper.ne("STATUS", DataStatus.delete.getKey());
            List<CustomerInfo> customerInfoList = customerInfoMapper.selectList(infoQueryWrapper);
            if (customerInfoList != null && customerInfoList.size() > 0) {
                throw new CustomException("该平台手机号为:" + customerInfo.getPhone() + "已注册");
            }
            DateTime date = DateUtil.date();
            Long userId = SecurityUtils.getUserId();
            if ("男".equals(customerInfo.getSex())) {
                customerInfo.setSex("0");
            } else if ("女".equals(customerInfo.getSex())) {
                customerInfo.setSex("1");
            }
            customerInfo.setNation("中国");
            customerInfo.setPlatformUid(SecurityUtils.getPlatformId());
            if (customerInfo.getRegion() != null) {
                Long[] region = customerInfo.getRegion();
                Long provinceCode = region[0];
                Long cityCode = region[1];
                Long areaCode = region[2];
                customerInfo.setProvinceCode(String.valueOf(provinceCode));
                customerInfo.setCityCode(String.valueOf(cityCode));
                customerInfo.setAreaCode(String.valueOf(areaCode));
            }
            customerInfo.setCreateTime(date);
            customerInfo.setCreateName(SecurityUtils.getUsername());
            customerInfo.setCreateUser(userId);
            customerInfo.setStatus(DataStatus.valid.getKey());
            this.save(customerInfo);
            Long customerUid = customerInfo.getCustomerUid();
            //添加客户账号
            CustomerInfoAccount customerInfoAccount = new CustomerInfoAccount();
            customerInfoAccount.setCustomerUid(customerUid);
            customerInfoAccount.setAccountName(customerInfo.getPhone());
            customerInfoAccount.setAccountPassword(SecurityUtils.encryptPassword(password));
            customerInfoAccount.setAccountHeadImg(customerInfo.getHeadImage());
            customerInfoAccount.setRegTime(date);
            customerInfoAccount.setRegIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
            customerInfoAccount.setPhone(customerInfo.getPhone());
            customerInfoAccount.setAccountStatus("1");
            customerInfoAccount.setCreateUser(userId);
            customerInfoAccount.setCreateName(SecurityUtils.getUsername());
            customerInfoAccount.setCreateDate(date);
            customerInfoAccount.setPlatformUid(SecurityUtils.getPlatformId());
            customerInfoAccount.setSourcePort("manager");
            customerInfoAccountService.save(customerInfoAccount);
            return true;
        } catch (Exception e) {
            log.error("新增失败", e);
            throw new CustomException(e.getMessage());
        }
    }


    /**
     * 计算rmf
     */
    @Override
    public CustomerRmfVo getRff(Long customerId) {
        CustomerInfo byId = this.getById(customerId);
        if (ObjectUtil.isEmpty(byId)) throw new BaseException("客户不存在");
        CustomerRmfVo vo = new CustomerRmfVo();
        BeanUtils.copyProperties(byId, vo);
        Date date = DateUtil.date();
        /**
         * 最近的一年
         */
        Date oleTime = DateUtils.startAddDay(date, -365);
        /**
         * r 最近一次消费(Recency) 1分/180天 2分/90天 3分/60天 4分/30天 5分/15天
         * f 消费频率 (Frequency)/年(是最近的365天)  1分/2次 2分/5次 3分/8次 4分/12次 5分/15次
         * m 消费金额 (Monetary)/年(是最近的365天) 1分/1000及一下 2分/大于1000小于5000 3分/大于5000小于10000 4分/20000及以上 5分/50000及以上 只算现金支付
         * 编号次序RFM,1代表高(大于2分)，0代表低(小于3分)
         *
         *	R	F	M
         * 重要价值	1	1	1	A
         * 重要发展	1	0	1	A
         * 重要保持	0	1	1	B
         * 重要挽留	0	0	1	B
         * 一般价值	1	1	0	B
         * 一般发展	1	0	0	B
         * 一般保持	0	1	0	C
         * 一般挽留	0	0	0	C
         */
        int r = 0;
        int f = 0;
        int m = 0;
        int rValue = 0;
        int fValue = 0;
        int mValue = 0;
        /**
         * 查询客户最近一次消费是什么时候
         */
        String time = customerInfoMapper.selectLatelyConsumptionByCustomerId(customerId);
        if (ObjectUtil.isEmpty(time)) {
            rValue = 1;
        } else {
            Date date2 = DateUtil.parseDateTime(time);
            vo.setRNumber(Convert.toStr(date2));
            /**
             * 计算是多少天
             */
            rValue = (int) ((date.getTime()-date2.getTime()) / (1000 * 3600 * 24));
            if (rValue<=15){
                rValue = 5;
            }else if (rValue <= 30){
                rValue = 4;
            } else if (rValue <= 60) {
                rValue = 3;
            } else if (rValue <= 90){
                rValue = 2;
            } else {
                rValue = 1;
            }
            if (rValue > 2) r = 1;
        }
        /**
         * 计算最近的消费频率
         */
        int frequency = customerInfoMapper.selectLatelyFrequencyByCustomerId(customerId, oleTime, date);
        if (frequency == 0) {
            fValue = 1;
        } else {
            if (2 >= frequency) fValue = 1;
            else if (5 >= frequency) fValue = 2;
            else if (8 >= frequency) fValue = 3;
            else if (12 >= frequency) fValue = 4;
            else fValue = 5;
            if (fValue > 2) f = 1;
        }
        /**
         * 计算最近的消费金额
         */
        Long monetary = customerInfoMapper.selectLatelyMonetaryByCustomerId(customerId, oleTime, date);

            mValue = 1;


            if (monetary>=100000) mValue = 1;
            if ( monetary >=500000) mValue = 2;
            if ( monetary >= 1000000) mValue = 3;
            if ( monetary>=2000000) mValue = 4;
            if ( monetary>=5000000) mValue = 5;
            if (mValue > 2) m = 1;

        vo.setMValue(mValue);
        vo.setFValue(fValue);
        vo.setRValue(rValue);
        vo.setFNumber(frequency);
        vo.setMNumber(MoneyUtils.changeF2B(monetary));
        if (r == 1) {
            if (f == 1) {
                if (m == 1) vo.setCostName("重要价值客户");
                else vo.setCostName("一般价值客户");
            } else {
                if (m == 1) vo.setCostName("重要发展客户");
                else vo.setCostName("一般发展客户");
            }
        } else {
            if (f == 1) {
                if (m == 1) vo.setCostName("重要保持客户");
                else vo.setCostName("一般保持客户");
            } else {
                if (m == 1) vo.setCostName("重要挽留客户");
                else vo.setCostName("一般挽留客户");
            }
        }
        /**
         * 查询往往期的
         */
        //vo.setList(customerServiceSubscribeRecordService.selectListLimitByCustomerId(customerId, 5));

        /**
         * 查询潜在标签
         */
//        List<CustomerHiddenLabel> customerHiddenLabels = customerHiddenLabelService.selectLabelByCustomerId(customerId);
//        if (CollectionUtil.isNotEmpty(customerHiddenLabels)) {
//            StringBuffer buffer = new StringBuffer("");
//            customerHiddenLabels.stream().distinct().forEach(vos -> buffer.append(vos.getLabelValue()));
//            vo.setHiddenTage(buffer.toString());
//        }
        vo.setHiddenTages(customerHiddenLabelService.selectHiddenTages(customerId));
        /**
         *查看客户标签
         */
        vo.setCustomerTags(customerLabelInfoService.getByCustomerId(customerId));
        return vo;
    }

    @Override
    public CustomerRmfVo getRmf(Long customerId) {
        CustomerRmfVo vo = new CustomerRmfVo();
        Date date = DateUtil.date();
        /**
         * 最近的一年
         */
        Date oleTime = DateUtils.startAddDay(date, -365);
        /**
         * r 最近一次消费(Recency) 1分/180天 2分/90天 3分/60天 4分/30天 5分/15天
         * f 消费频率 (Frequency)/年(是最近的365天)  1分/2次 2分/5次 3分/8次 4分/12次 5分/15次
         * m 消费金额 (Monetary)/年(是最近的365天) 1分/1000及一下 2分/大于1000小于5000 3分/大于5000小于10000 4分/20000及以上 5分/50000及以上 只算现金支付
         * 编号次序RFM,1代表高(大于2分)，0代表低(小于3分)
         *
         *	R	F	M
         * 重要价值	1	1	1	A
         * 重要发展	1	0	1	A
         * 重要保持	0	1	1	B
         * 重要挽留	0	0	1	B
         * 一般价值	1	1	0	B
         * 一般发展	1	0	0	B
         * 一般保持	0	1	0	C
         * 一般挽留	0	0	0	C
         */
        int r = 0;
        int f = 0;
        int m = 0;
        int rValue = 0;
        int fValue = 0;
        int mValue = 0;
        /**
         * 查询客户最近一次消费是什么时候
         */
        String time = customerInfoMapper.selectLatelyConsumptionByCustomerId(customerId);
        if (ObjectUtil.isEmpty(time)) {
            rValue = 1;
            vo.setRNumber("");
        } else {
            Date date2 = DateUtil.parseDateTime(time);
            vo.setRNumber(Convert.toStr(date2));
            /**
             * 计算是多少天
             */
            rValue = (int) ((date.getTime()-date2.getTime()) / (1000 * 3600 * 24));
            if (rValue<=15){
                rValue = 5;
            }else if (rValue <= 30){
                rValue = 4;
            } else if (rValue <= 60) {
                rValue = 3;
            } else if (rValue <= 90){
                rValue = 2;
            } else {
                rValue = 1;
            }
            if (rValue > 2) r = 1;
        }
        /**
         * 计算最近的消费频率
         */
        int frequency = customerInfoMapper.selectLatelyFrequencyByCustomerId(customerId, oleTime, date);
        if (frequency == 0) {
            fValue = 1;
        } else {
            if (2 >= frequency) fValue = 1;
            else if (5 >= frequency) fValue = 2;
            else if (8 >= frequency) fValue = 3;
            else if (12 >= frequency) fValue = 4;
            else fValue = 5;
            if (fValue > 2) f = 1;
        }
        /**
         * 计算最近的消费金额
         */
        Long monetary = customerInfoMapper.selectLatelyMonetaryByCustomerId(customerId, oleTime, date);

        mValue = 1;


        if (monetary>=100000) mValue = 1;
        if ( monetary >=500000) mValue = 2;
        if ( monetary >= 1000000) mValue = 3;
        if ( monetary>=2000000) mValue = 4;
        if ( monetary>=5000000) mValue = 5;
        if (mValue > 2) m = 1;

        vo.setMValue(mValue);
        vo.setMNumber(MoneyUtils.changeF2B(monetary));
        vo.setFValue(fValue);
        vo.setFNumber(frequency);
        vo.setRValue(rValue);

        if (r == 1) {
            if (f == 1) {
                if (m == 1) vo.setCostName("重要价值客户");
                else vo.setCostName("一般价值客户");
            } else {
                if (m == 1) vo.setCostName("重要发展客户");
                else vo.setCostName("一般发展客户");
            }
        } else {
            if (f == 1) {
                if (m == 1) vo.setCostName("重要保持客户");
                else vo.setCostName("一般保持客户");
            } else {
                if (m == 1) vo.setCostName("重要挽留客户");
                else vo.setCostName("一般挽留客户");
            }
        }

        return vo;
    }

}
